package com.cc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cc.comm.util.JwtTokenUtil;
import com.cc.dto.UserLoginDTO;
import com.cc.entity.Employees;
import com.cc.entity.LoginUser;
import com.cc.service.EmployeesService;
import com.cc.mapper.EmployeesMapper;
import com.cc.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author 晓东√
 * @description 针对表【employees(员工表 )】的数据库操作Service实现
 * @createDate 2024-12-16 14:10:02
 */
@Service
@Slf4j
public class EmployeesServiceImpl extends ServiceImpl<EmployeesMapper, Employees>
        implements EmployeesService {
    @Autowired
    EmployeesMapper employeesMapper;
    //认证管理器
    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Autowired
    RedisService redisService;

    @Override
    public Map login(UserLoginDTO userLogin) {

        //生成一个包含账号密码的认证信息
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userLogin.getUserName(),userLogin.getPassword());
        //进行校验
        //AuthenticationManager校验这个认证信息，返回一个已认证的Authentication
        Authentication authentication = authenticationManager.authenticate(authenticationToken);

        //如果认证没通过，给出对应的提示（如果authenticate为null，则认证不通过）
        if (Objects.isNull(authentication)) {
            log.error("登录失败");
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        String token = jwtTokenUtil.generateToken(loginUser);
        //将用户信息保存到redis中
        redisService.set("loginUser:" + loginUser.getEmployees().getLoginName(), loginUser);
        Map<String,String> map = new HashMap<>();
        map.put("token", token);
        return map;
    }
}




